package com.kehutong.house.service;

import com.kehutong.house.entity.Community;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.util.Objects;



@WebService("/basic/community/service/api")
public class CommunityServiceApi {
	private static final Logger logger = LoggerFactory.getLogger(CommunityServiceApi.class);
	@Inject
	private JdbcSession jdbcSession;


    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) {
    	return jdbcSession.findArray(Community.class)
    			.eq(jsonObject, "area_id", "parent_id")
    			.like(jsonObject, "name", "viewName", "parent_ids", "area_ids")
				.eq("deleted", false)
				.exe();
    }

    @ReqMapping("/get")
    public Object get(Community item) {
    	return item;
    }

    @Bean(newInstance=true, copy=true)
    @ReqMapping("/save")
    public Object save(Community community) {
		// 增加校验不允许有相同的小区名称
		Community item = jdbcSession.findOne(Community.class)
				.eq("name", community.getName())
				.eq("deleted", false)
				.exe();

		if(Objects.nonNull(item)){
			return Result.error(0, "已有当前小区名称，请修改后重试");
		}
    	jdbcSession.insert(community);
    	return Result.success(community);
    }

    @Bean(copy=true)
    @ReqMapping("/update")
    public Object update(Community community) throws Exception {
		// 增加校验不允许有相同的小区名称
		Community item = jdbcSession.findOne(Community.class)
				.eq("name", community.getName())
				.noEq("id", community.getId())
				.eq("deleted", false)
				.exe();

		if(Objects.nonNull(item)){
			return Result.error(0, "已有当前小区名称，请修改后重试");
		}
    	jdbcSession.updateById(community);
    	return Result.success(community);
    }

    @ReqMapping("/delete")
	public Object delete(Community item) {
		item.setDeleted(true);
		return jdbcSession.updateById(item);
	}

    public boolean isCommunityExist(String communityNo) {
    	if (Objects.isEmpty(communityNo)) {
    		return false;
    	}

    	Community community = jdbcSession.findById(Community.class, communityNo);

    	return Objects.nonNull(community);

    }

	@ReqMapping("/pageList")
	public Object pageList(JSONObject json) {
		logger.debug("{}=========", this.hashCode());
		Page<Community> page = jdbcSession.findPage(Community.class)
				.eq("deleted", false)
				.in(json, "id")
				.in(json, "parent_id")
				.between("createTime", json, "beginTime", "endTime")
				.like(json, "name", "area_ids")
				.page(json).exe();
		return page;
	}
}
